{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 环境搭建\n",
    "- 安装pyenv做本地环境管理\n",
    "- 将本地目录设置为需要的python版本\n",
    "- 安装Langchain包"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 环境测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world!\n"
     ]
    }
   ],
   "source": [
    "print(\"hello world!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found existing installation: langchain 0.1.12\n",
      "Uninstalling langchain-0.1.12:\n",
      "  Successfully uninstalled langchain-0.1.12\n",
      "Found existing installation: openai 1.14.0\n",
      "Uninstalling openai-1.14.0:\n",
      "  Successfully uninstalled openai-1.14.0\n"
     ]
    }
   ],
   "source": [
    "! pip uninstall langchain -y\n",
    "! pip uninstall openai -y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting langchain==0.0.279\n",
      "  Obtaining dependency information for langchain==0.0.279 from https://files.pythonhosted.org/packages/fb/c3/01030edac782a84c3e8d76053bc31073f73f5454b18de14848aab5aca354/langchain-0.0.279-py3-none-any.whl.metadata\n",
      "  Using cached langchain-0.0.279-py3-none-any.whl.metadata (14 kB)\n",
      "Requirement already satisfied: PyYAML>=5.3 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (6.0.1)\n",
      "Requirement already satisfied: SQLAlchemy<3,>=1.4 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (2.0.23)\n",
      "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (3.8.6)\n",
      "Requirement already satisfied: dataclasses-json<0.6.0,>=0.5.7 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (0.5.14)\n",
      "Collecting langsmith<0.1.0,>=0.0.21 (from langchain==0.0.279)\n",
      "  Obtaining dependency information for langsmith<0.1.0,>=0.0.21 from https://files.pythonhosted.org/packages/97/cd/1c618f89d3fcbb375c99a3ea950bffba8a01862cc0f0ab5032dfb95e8d1e/langsmith-0.0.92-py3-none-any.whl.metadata\n",
      "  Using cached langsmith-0.0.92-py3-none-any.whl.metadata (9.9 kB)\n",
      "Requirement already satisfied: numexpr<3.0.0,>=2.8.4 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (2.8.8)\n",
      "Requirement already satisfied: numpy<2,>=1 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (1.26.1)\n",
      "Requirement already satisfied: pydantic<3,>=1 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (1.10.14)\n",
      "Requirement already satisfied: requests<3,>=2 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (2.31.0)\n",
      "Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from langchain==0.0.279) (8.2.3)\n",
      "Requirement already satisfied: attrs>=17.3.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (23.1.0)\n",
      "Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (3.3.2)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (6.0.4)\n",
      "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (4.0.3)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (1.9.2)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (1.4.0)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.0.279) (1.3.1)\n",
      "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from dataclasses-json<0.6.0,>=0.5.7->langchain==0.0.279) (3.20.1)\n",
      "Requirement already satisfied: typing-inspect<1,>=0.4.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from dataclasses-json<0.6.0,>=0.5.7->langchain==0.0.279) (0.9.0)\n",
      "Requirement already satisfied: typing-extensions>=4.2.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from pydantic<3,>=1->langchain==0.0.279) (4.8.0)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests<3,>=2->langchain==0.0.279) (3.4)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests<3,>=2->langchain==0.0.279) (2.1.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests<3,>=2->langchain==0.0.279) (2023.7.22)\n",
      "Requirement already satisfied: packaging>=17.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from marshmallow<4.0.0,>=3.18.0->dataclasses-json<0.6.0,>=0.5.7->langchain==0.0.279) (23.2)\n",
      "Requirement already satisfied: mypy-extensions>=0.3.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.6.0,>=0.5.7->langchain==0.0.279) (1.0.0)\n",
      "Using cached langchain-0.0.279-py3-none-any.whl (1.6 MB)\n",
      "Using cached langsmith-0.0.92-py3-none-any.whl (56 kB)\n",
      "Installing collected packages: langsmith, langchain\n",
      "  Attempting uninstall: langsmith\n",
      "    Found existing installation: langsmith 0.1.25\n",
      "    Uninstalling langsmith-0.1.25:\n",
      "      Successfully uninstalled langsmith-0.1.25\n",
      "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
      "langchain-openai 0.0.8 requires openai<2.0.0,>=1.10.0, which is not installed.\n",
      "langchain-experimental 0.0.49 requires langchain<0.2,>=0.1, but you have langchain 0.0.279 which is incompatible.\n",
      "langserve 0.0.51 requires langchain>=0.0.333, but you have langchain 0.0.279 which is incompatible.\n",
      "langchain-core 0.1.31 requires langsmith<0.2.0,>=0.1.0, but you have langsmith 0.0.92 which is incompatible.\n",
      "langchain-community 0.0.28 requires langsmith<0.2.0,>=0.1.0, but you have langsmith 0.0.92 which is incompatible.\u001b[0m\u001b[31m\n",
      "\u001b[0mSuccessfully installed langchain-0.0.279 langsmith-0.0.92\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.0\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "! pip install --upgrade langchain==0.0.279 -i https://pypi.org/simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#如果没有科学上网，可以用这个命令安装\n",
    "! pip install --upgrade langchain==0.0.279 -i https://pypi.tuna.tsinghua.edu.cn/simple"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 依赖安装\n",
    "- 安装openai的api包\n",
    "- 或者使用Baichuan、ChatGLM这样的开源包"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "pip install openai\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install openai==v0.28.1 -i https://pypi.org/simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Collecting openai==0.27.8\n",
      "  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/67/78/7588a047e458cb8075a4089d721d7af5e143ff85a2388d4a28c530be0494/openai-0.27.8-py3-none-any.whl (73 kB)\n",
      "Requirement already satisfied: requests>=2.20 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from openai==0.27.8) (2.31.0)\n",
      "Requirement already satisfied: tqdm in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from openai==0.27.8) (4.66.1)\n",
      "Requirement already satisfied: aiohttp in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from openai==0.27.8) (3.8.6)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests>=2.20->openai==0.27.8) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests>=2.20->openai==0.27.8) (3.4)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests>=2.20->openai==0.27.8) (2.1.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from requests>=2.20->openai==0.27.8) (2023.7.22)\n",
      "Requirement already satisfied: attrs>=17.3.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp->openai==0.27.8) (23.1.0)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp->openai==0.27.8) (6.0.4)\n",
      "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp->openai==0.27.8) (4.0.3)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp->openai==0.27.8) (1.9.2)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp->openai==0.27.8) (1.4.0)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages (from aiohttp->openai==0.27.8) (1.3.1)\n",
      "Installing collected packages: openai\n",
      "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
      "doctran 0.0.14 requires tiktoken<0.6.0,>=0.5.0, but you have tiktoken 0.6.0 which is incompatible.\n",
      "langchain-openai 0.0.8 requires openai<2.0.0,>=1.10.0, but you have openai 0.27.8 which is incompatible.\u001b[0m\u001b[31m\n",
      "\u001b[0mSuccessfully installed openai-0.27.8\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.0\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "! pip install --upgrade openai==0.27.8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#如果没有科学上网，可以使用这个命令安装\n",
    "! pip install openai==0.27.8 -i https://pypi.tuna.tsinghua.edu.cn/simple"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 引入openai key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"OPENAI_KEY\"] = \"sk-ss\"\n",
    "os.environ[\"OPENAI_API_BASE\"] = \"https://ai-yyds.com/v1\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 从环境变量中读取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OPENAI_API_KEY: sk-pQ7osw5XrDY1Ejsx99EcEe5f58D04dDeB387B8E6B3C10bDb\n",
      "OPENAI_PROXY: https://ai-yyds.com/v1\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "openai_api_key = os.getenv(\"OPENAI_KEY\")\n",
    "openai_api_base = os.getenv(\"OPENAI_API_BASE\")\n",
    "print(\"OPENAI_API_KEY:\", openai_api_key)\n",
    "print(\"OPENAI_PROXY:\", openai_api_base)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 运行前查看下安装情况"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name: langchain\n",
      "Version: 0.0.279\n",
      "Summary: Building applications with LLMs through composability\n",
      "Home-page: https://github.com/langchain-ai/langchain\n",
      "Author: \n",
      "Author-email: \n",
      "License: MIT\n",
      "Location: /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages\n",
      "Requires: aiohttp, dataclasses-json, langsmith, numexpr, numpy, pydantic, PyYAML, requests, SQLAlchemy, tenacity\n",
      "Required-by: langchain-experimental, langserve\n",
      "Name: openai\n",
      "Version: 0.27.8\n",
      "Summary: Python client library for the OpenAI API\n",
      "Home-page: https://github.com/openai/openai-python\n",
      "Author: OpenAI\n",
      "Author-email: support@openai.com\n",
      "License: \n",
      "Location: /Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages\n",
      "Requires: aiohttp, requests, tqdm\n",
      "Required-by: doctran, langchain-openai\n"
     ]
    }
   ],
   "source": [
    "! pip show langchain\n",
    "! pip show openai"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### openai 官方SDK"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您好！我是一个开源的大型语言模型，由 OpenAI 创建，名叫 ChatGPT。我的训练包括了大量的文本数据，所以我可以在很多主题上进行对话和回答问题，比如科技、文学和日常知识等等。虽然我试图提供有用和准确的信息，但我并不完美，有时也会犯错。我的目的是为了帮助用户解答问题，并在交谈中提供友好和丰富的体验。我总是在不断地学习和适应以提供更好的回答和建议。如有任何问题或需要帮助，请随时告诉我！\n"
     ]
    }
   ],
   "source": [
    "#使用openai的官方sdk\n",
    "import openai\n",
    "import os\n",
    "\n",
    "openai.api_base = os.getenv(\"OPENAI_API_BASE\")\n",
    "openai.api_key = os.getenv(\"OPENAI_KEY\")\n",
    "\n",
    "messages = [\n",
    "{\"role\": \"user\", \"content\": \"介绍下你自己\"}\n",
    "]\n",
    "\n",
    "res = openai.ChatCompletion.create(\n",
    "model=\"gpt-4-1106-preview\",\n",
    "messages=messages,\n",
    "stream=False,\n",
    ")\n",
    "\n",
    "print(res['choices'][0]['message']['content'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用langchain调用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\n\\n我是一名来自广东的大学生，性格开朗、乐观向上。我喜欢阅读、旅行和运动，对新事物充满好奇心，喜欢不断学习和挑战自己。在校期间，我担任过学生会干部，参加过多项社会实践活动，积累了一定的组织能力和团队合作精神。我也曾在一家公司实习过，学习了一些专业知识和实践经验。我希望能够通过不断努力，提升自己的能力，为将来的工作做好准备。'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#hello world\n",
    "from langchain.llms import OpenAI\n",
    "import os\n",
    "\n",
    "api_base = os.getenv(\"OPENAI_API_BASE\")\n",
    "api_key = os.getenv(\"OPENAI_KEY\")\n",
    "llm = OpenAI(\n",
    "    model=\"gpt-3.5-turbo-instruct\",\n",
    "    temperature=0,\n",
    "    openai_api_key=api_key,\n",
    "    openai_api_base=api_base\n",
    "    )\n",
    "llm.predict(\"介绍下你自己\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 起名大师"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个起名大师,请模仿示例起3个中国特色的名字,比如男孩经常被叫做狗蛋,女孩经常被叫做翠花\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\n男孩: 龙飞、铁柱、小虎\\n女孩: 玉兰、梅香、小红梅'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#起名大师\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "import os\n",
    "api_base = os.getenv(\"OPENAI_API_BASE\")\n",
    "api_key = os.getenv(\"OPENAI_KEY\")\n",
    "llm = OpenAI(\n",
    "    model=\"gpt-3.5-turbo-instruct\",\n",
    "    temperature=0,\n",
    "    openai_api_key=api_key,\n",
    "    openai_api_base=api_base\n",
    "    )\n",
    "prompt = PromptTemplate.from_template(\"你是一个起名大师,请模仿示例起3个{county}名字,比如男孩经常被叫做{boy},女孩经常被叫做{girl}\")\n",
    "message = prompt.format(county=\"中国特色的\",boy=\"狗蛋\",girl=\"翠花\")\n",
    "print(message)\n",
    "llm.predict(message)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 格式化输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['hi', 'bye']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.schema import BaseOutputParser\n",
    "#自定义class，继承了BaseOutputParser\n",
    "class CommaSeparatedListOutputParser(BaseOutputParser):\n",
    "    \"\"\"Parse the output of an LLM call to a comma-separated list.\"\"\"\n",
    "\n",
    "\n",
    "    def parse(self, text: str):\n",
    "        \"\"\"Parse the output of an LLM call.\"\"\"\n",
    "        return text.strip().split(\", \")\n",
    "\n",
    "CommaSeparatedListOutputParser().parse(\"hi, bye\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个起名大师,请模仿示例起3个具有美国男孩特色的名字,示例：男孩常用名sam,女孩常用名lucy。请返回以逗号分隔的列表形式。仅返回逗号分隔的列表，不要返回其他内容。\n",
      "\n",
      "\n",
      "jack, michael, jason\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['jack', ' michael', ' jason']"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#起名大师，输出格式为一个数组\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "import os\n",
    "from langchain.schema import BaseOutputParser\n",
    "\n",
    "#自定义类\n",
    "class CommaSeparatedListOutputParser(BaseOutputParser):\n",
    "    \"\"\"Parse the output of an LLM call to a comma-separated list.\"\"\"\n",
    "\n",
    "    def parse(self, text: str):\n",
    "        \"\"\"Parse the output of an LLM call.\"\"\"\n",
    "        print(text)\n",
    "        return text.strip().split(\",\")\n",
    "\n",
    "\n",
    "api_base = os.getenv(\"OPENAI_API_BASE\")\n",
    "api_key = os.getenv(\"OPENAI_KEY\")\n",
    "llm = OpenAI(\n",
    "    model=\"gpt-3.5-turbo-instruct\",\n",
    "    temperature=0,\n",
    "    openai_api_key=api_key,\n",
    "    openai_api_base=api_base\n",
    "    )\n",
    "prompt = PromptTemplate.from_template(\"你是一个起名大师,请模仿示例起3个具有{county}特色的名字,示例：男孩常用名{boy},女孩常用名{girl}。请返回以逗号分隔的列表形式。仅返回逗号分隔的列表，不要返回其他内容。\")\n",
    "message = prompt.format(county=\"美国男孩\",boy=\"sam\",girl=\"lucy\")\n",
    "print(message)\n",
    "strs = llm.predict(message)\n",
    "CommaSeparatedListOutputParser().parse(strs)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
    